package top.maof.lightsearch.handle;

import lombok.Data;
import top.maof.lightsearch.annotation.Key;
import top.maof.lightsearch.annotation.Property;
import top.maof.lightsearch.annotation.Type;
import top.maof.lightsearch.exception.NoKeyException;
import top.maof.lightsearch.exception.NoTypeException;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 实体类模型,用来保存业务代码的实体类中的信息
 * 包括 类注解信息,对象值,属性信息等
 */
@Data
public class Entity<T> {
    private T t;
    private List<Field> fields;
    private Type type;


    public T getT() {
        return t;
    }

    public Entity(T t) throws NoTypeException, NoKeyException {
        this.t = t;

        this.type = t.getClass().getDeclaredAnnotation(Type.class);
        if (this.type == null) {
            throw new NoTypeException();
        }


        this.fields = Arrays.asList(t.getClass().getDeclaredFields()).stream().filter((Predicate<Field>) field -> {
            Property property = field.getAnnotation(Property.class);
            Key key = field.getAnnotation(Key.class);
            return key != null || property != null;
        }).collect(Collectors.toList());

        if (this.fields.size() == 0) {
            throw new NoKeyException();
        }

    }


    public Entity(Class<T> clazz) throws NoTypeException, NoKeyException, IllegalAccessException, InstantiationException {
        this.t = clazz.newInstance();

        this.type = clazz.getDeclaredAnnotation(Type.class);
        if (this.type == null) {
            throw new NoTypeException();
        }

        this.fields = Arrays.asList(t.getClass().getDeclaredFields()).stream().filter((Predicate<Field>) field -> {
            Property property = field.getAnnotation(Property.class);
            Key key = field.getAnnotation(Key.class);
            return key != null || property != null;
        }).collect(Collectors.toList());

        if (this.fields.size() == 0) {
            throw new NoKeyException();
        }

    }
}
